package com.example.demo.service.impl;

import com.example.demo.service.FloorPlainService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;


@Service
public class FloorPlainServiceImpl implements FloorPlainService {

    @Override
    public void putPic (MultipartFile file, String title) {
        try{
            File dir = new File("flootPlain");
            if(!dir.exists()) {
                dir.mkdirs();
            }
            String path = dir.getAbsolutePath() + "\\" + title;
            System.out.println(path);
            File photos = new File(path);
            if(!photos.exists()) {
                photos.mkdirs();
            }

            String imgName = file.getOriginalFilename();
            String path1 = path + "\\" + imgName;
            System.out.println(imgName);
            System.out.println(path1);
            //文件实现上传
            file.transferTo(new File(path1));

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public byte[] getPic(String title) {
        try{
            File dir = new File("flootPlain/"+title);
            File[] flist = null;
            byte[] data = null;
            if (dir.exists() && dir.isDirectory()) {
                flist = dir.listFiles();
                for (File f : flist) {
                    System.out.println(f.length());
                    try {
                        FileInputStream fis = new FileInputStream(f);
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        int len;
                        byte[] buffer = new byte[1024];
                        while ((len = fis.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }

                        data = baos.toByteArray();

                        fis.close();
                        baos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(Arrays.toString(data));
                }
            }
            return data;
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
